package com.dianda.generic.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;

import java.util.Date;

/**
 * Json处理工具类
 * Create by The_Answer on 2018/4/13.
 */
public class JsonUtils {

    private static SerializeConfig mapping = new SerializeConfig();

    private static String dateFormat;

    static {
        dateFormat = "yyyy-MM-dd HH:mm:ss";
        mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
    }

    /**
     * @param obj //对象模型
     * @return String   //转换完毕的字符串
     * @Title: objToJson
     * @Description: 将对象转换为JSON字符串
     */
    public static String objToJson(Object obj) {
        String str = JSON.toJSONString(obj, mapping, SerializerFeature.WriteMapNullValue);
        return str;
    }

    /**
     * @param text  //需要转换的字符串
     * @param clazz //转换时使用的实体类型
     * @return
     * @Title: jsonToObj
     * @Description: 将JSON字符串转换为对象
     */
    public static <T> T jsonToObj(String text, Class<T> clazz) {
        T t = JSON.parseObject(text, clazz);
        return t;
    }
}
